package controllers

import (
	"api01/models"
	"api01/resources"
	"api01/util"
	"encoding/json"
	"github.com/astaxie/beego/validation"
)

type GroupController struct {
	BaseController
}

// @Title List
// @Description role list
// @Param	keyword		query 	string	true		"The keyword for search"
// @Success 200 {int} []models.Group
// @Failure 403 error
// @router /  [get]
func  (this *GroupController) Index ()  {
	groups, err := models.GetGroupAll()
	util.CheckError(err)
	ret := resources.BuildGroupDataStruct(groups)
	util.OutPutSuccess(ret)
}

// @Title Add
// @Description add role
// @Param	name  	form 	string	true		"role name"
// @Success 200 {int}  success
// @Failure 403 error
// @router /  [post]
func  (this *GroupController) Store ()  {
	name := this.GetString("name")
	pid, _ := this.GetInt("pid")
	valid := validation.Validation{}
	valid.Required(name, "name").Message("用户组名称不能为空")
	if valid.HasErrors() {
		util.OutPutError(401,valid.Errors[0].Message)
		return
	}
	group := models.Group{
		Name: name,
		Pid:  pid,
	}
	err := models.AddGroupOne(&group)
	util.CheckError(err)
	util.OutPutSuccess(map[string]string{"message":"创建成功"})
}

// @Title Show
// @Description show role
// @Param	id  	path 	string	true		"role id"
// @Success 200 {int}  success
// @Failure 403 error
// @router /:id  [get]
func  (this *GroupController) Show ()  {
	id, err := this.GetInt(":id")
	if err != nil {
		util.OutPutError(401,"ID异常")
	}
	role, err := models.GetGroupById(id)
	util.CheckError(err)
	util.OutPutSuccess(role)
}

// @Title Update
// @Description update role
// @Param	id  	path 	string	true		"role id"
// @Param	name  	form 	string	true		"role name"
// @Success 200 {int}  success
// @Failure 403 error
// @router /:id  [put]
func  (this *GroupController) Update ()  {
	id, err := this.GetInt(":id")
	if err != nil {
		util.OutPutError(401,"ID异常")
	}
	var group models.Group
	json.Unmarshal(this.Ctx.Input.RequestBody, &group)

	valid := validation.Validation{}
	valid.Required(group.Name, "name").Message("角色名称不能为空")
	if valid.HasErrors() {
		util.OutPutError(401,valid.Errors[0].Message)
		return
	}
	err = models.UpdateGroupById(id, group.Name)
	util.CheckError(err)
	util.OutPutSuccess(map[string]string{"message":"修改成功"})
}

// @Title Destroy
// @Description destroy role
// @Param	id  	path 	string	true		"role id"
// @Success 200 {int}  success
// @Failure 403 error
// @router /:id  [delete]
func  (this *GroupController) Destroy ()  {
	id, err := this.GetInt(":id")
	if err != nil {
		util.OutPutError(401,"ID异常")
	}
	err = models.DeleteGroupById(id)
	util.CheckError(err)
	util.OutPutSuccess(map[string]string{"message":"删除成功"})
}
